package com.wenxixuanwu.fruitstore.controller;

import com.wenxixuanwu.fruitstore.entity.User;
import com.wenxixuanwu.fruitstore.mapper.UserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    @RequestMapping("/insert")
    public int insert(@RequestBody User user) {
        User users = mapper.getByUserName(user.getUsername());
        if (user.getUsername().length() == 0 || user.getPassword().length() == 0) {
            return 3;
        }
        if (users == null) {
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            System.out.println(user.getPassword());
            mapper.insert(user);
            System.out.println(user);
            return 1;
        }
        return 2;
    }

    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session) {
        User users = mapper.getByUserName(user.getUsername());
        if (users != null) {
            if (users.getPassword().equals(DigestUtils.md5Hex(user.getPassword()))) {
                session.setAttribute("u", users);
                return 1;
            }
        }
        return 3;
    }

    @RequestMapping("/login/nick")
    public User loginNick(HttpSession session) {
        User user = (User) session.getAttribute("u");
        if (user == null) {
            String nick = "游客"+new Random().nextInt(100000);
           User users = new User();
           users.setNick(nick);
            return users;
        } else {
            return (User)session.getAttribute("u");
        }
    }

    @GetMapping("/currentUser")
    public User getById(HttpSession session){
        User user = (User)session.getAttribute("u");
        return mapper.getById(user.getId());
    }

    @GetMapping("/loginOut")
    public Integer loginOut(HttpSession session){
        session.removeAttribute("u");
        return 1;
    }
}
